from cgi import escape
import re

__all__ = ["SmartMessage", "SmartMessageHelper"]
class SmartMessage(object):
    
    url_re = re.compile(r'((http|https|ftp|gopher|news)://[^ \'")>]*)')
    
    def __init__(self, message, last_time):
        self.message = message
        self.time = message.time
        self.nick = message.nick
        self.type = message.message_type
        if self.type in ['message','action']:
            self.line = self.linkify(message.line)
        else:
            self.line = message.line
        if last_time is not None:
            self.last_time = last_time
        else:
            self.last_time = None

    def day_changed(self):
        changed = True
        if self.last_time is not None:
            this_tuple = (self.time.year, self.time.month, self.time.day)
            last_tuple = (self.last_time.year, self.last_time.month, self.last_time.day)
            if this_tuple == last_tuple:
                changed = False
        return changed

    def linkify(self, text):
        text = escape(text)
        return self.url_re.sub(r'<a href="\1">\1</a>', text)
        
    @property
    def datestr(self):
        return self.time.strftime("%Y-%m-%d")
        
class SmartMessageHelper(object):
    
    def __init__(self):
        self.last_time = None
        
    def __call__(self, message):
        m = SmartMessage(message, self.last_time)
        self.last_time = message.time
        return m